package com.nlx.notes.configuer;

import com.nlx.notes.support.interceptor.SecurityBodyInterceptor;
import com.nlx.notes.support.interceptor.TokenInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {

    private final TokenInterceptor tokenInterceptor;

    private final SecurityBodyInterceptor securityBodyInterceptor;

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*"); // 允许所有前端地址，生产环境建议限定
        config.setAllowCredentials(true);
        config.addAllowedHeader("*");        // 允许所有请求头
        config.addAllowedMethod("*");        // 允许所有请求方法 GET, POST, PUT...
        config.setMaxAge(3600L);             // 缓存时间1小时
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config); // 所有路径都支持跨域
        return new CorsFilter(source);
    }

    /**
     * 开启方法级别参数校验
     * @return MethodValidationPostProcessor
     */
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }

//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        registry.addMapping("/**") // 对所有路径开放
//                .allowedOriginPatterns("*") // 允许的来源
//                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的请求方法
//                .allowedHeaders("*") // 允许的请求头
//                .allowCredentials(true) // 允许发送凭证
//                .maxAge(3600); // 预检请求的有效时间（单位：秒）
//    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor)
                .addPathPatterns("/**") // 拦截所有请求
                .excludePathPatterns(
                        "/login/v1/user",
                        "/sms/send-sms",
                        "/gold/dynamic/v1/price/metrics"
                ); // 排除登录、注册、文档等

        registry.addInterceptor(securityBodyInterceptor)
                .addPathPatterns("/**");
    }

}